using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Configuration;
using CLFramework.Configuration;

namespace CLFramework.ScheduledTasks
{
    public class TaskConfiguration : ConfigurationBase
    {

        public static TaskConfiguration GetConfig()
        {
            return GetConfig<TaskConfiguration>("tasks", true) as TaskConfiguration;
        }

        private List<TaskThread> taskThreads = new List<TaskThread>();
        private Dictionary<string, ITaskModule> modules = new Dictionary<string,ITaskModule>();

        public List<TaskThread> TaskThreads
        {
            get {
                return taskThreads;
            }
        }

        public Dictionary<string, ITaskModule> Modules
        {
            get {
                return modules;
            }
        }

        protected override void LoadValuesFromConfigurationXml(XmlNode node)
        {
            foreach (XmlNode child in node.ChildNodes)
            {
                switch (child.Name.ToLower())
                {
                    case "modules":
                        LoadModules<ITaskModule>(child, ref modules);
                        break;

                    case "threads":
                        this.LoadThreads(child);
                        break;
                }
            }
        }

        private void LoadThreads(XmlNode tasksNode)
        {
            this.taskThreads.Clear();
            foreach (XmlNode node in tasksNode.ChildNodes)
            {
                if (node.Name.ToLower() == "thread")
                {
                    TaskThread thread = new TaskThread(node);
                    this.taskThreads.Add(thread);
                    foreach (XmlNode threadNodes in node.ChildNodes)
                    {
                        if (threadNodes.Name.ToLower() == "task")
                        {
                            XmlAttribute attribute = threadNodes.Attributes["type"];
                            Type type = Type.GetType(attribute.Value);
                            if (type != null)
                            {
                                Task task = new Task(type, threadNodes);
                                thread.AddTask(task);
                            }
                        }
                    }
                }
            }
        }
    }
}
